package com.zrf.testchatgpt.controller;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zrf.testchatgpt.service.IConfigService;
import com.zrf.testchatgpt.translate.demo.TransApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;


@Controller
@RequestMapping("/baidu")
@Slf4j
@RequiresRoles("admin")
public class TranslateController {

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    public  static final String APP_ID = "20230416001644227";
    public  static final String SECURITY_KEY = "_tQjnNVD0V3QH4Rpt_8C";
    @Autowired
    IConfigService iSysConfigService;
    @PostMapping("/Translate")
    @ResponseBody
    public Map<String,Object> toTranslate(@RequestParam Map<String, Object> map) throws InterruptedException {
        String appid = iSysConfigService.selectConfigByKey("baidu_appid");
        String secret = iSysConfigService.selectConfigByKey("baidu_secret");
        log.info("appid:"+appid);
        log.info("secret:"+secret);
        TransApi api = new TransApi(appid, secret);
        //创建线程池，核心线程1，最大线程数10，存货时间1分钟，任务队列5，默认的线程工厂，拒绝策略为拒绝并抛出异常
        ExecutorService executorService = new ThreadPoolExecutor(1, 10, 1, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        for (String key : map.keySet()) {
            Object childMap = map.get(key);
            StringBuilder builder = new StringBuilder();
                //需要翻译的中文
                builder.append(childMap).append("\n");
            //执行线程
            executorService.execute(() -> {
                String result = api.getTransResult(builder.toString(), "auto", "en");
                System.out.println("result:" + result);
                //转成map
                Map<String, String> mapResult = JSON.parseObject(result, Map.class);
                List<Map<String, String>> transResult = (List<Map<String, String>> ) JSONArray.parse(JSON.toJSONString(mapResult.get("trans_result")));
                    //获取翻译结果
                    String transQuery = (String) transResult.get(0).get("dst");
                    try {
                        //解码
                        transQuery = URLDecoder.decode(transQuery, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    map.put(key, transQuery);
            });
            //线程池等待时间，这里即阻塞2秒
            executorService.awaitTermination(1, TimeUnit.SECONDS);
        }
        //任务执行完成后关闭线程池
        executorService.shutdown();
        return map;
    }
}
